package com.apexedu.biz.service.impl;

import com.apexedu.biz.entity.TAccessAppReg;
import com.apexedu.biz.entity.client.CommandResult;
import com.apexedu.biz.entity.client.JzgDsfjc;
import com.apexedu.biz.entity.client.OrgDsfjc;
import com.apexedu.biz.entity.client.StuDsfjc;
import com.apexedu.framework.dao.BaseDao;
import com.apexedu.framework.util.ConfigUtil;
import com.apexedu.framework.util.DBUtil;
import com.apexedu.support.cache.CacheUtils;
import com.apexedu.util.StringUtil;
import com.apexedu.util.crypto.CipherUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 对资源的操作，都单独提取到这个类了。
 * User: 杨建亮
 * Date: 13-12-13  下午4:29
 */
public abstract class ResourceShmyServiceImpl {

    @SuppressWarnings("unused")
    private static final Log LOG = LogFactory.getLog(ResourceShmyServiceImpl.class);

    public static final String SecKey = CipherUtil.getAESKeyAsString("ApexAuCAuthKey"); // 和AuthClient客户端约定好的对称加密密钥
    private static final String portalKey = ConfigUtil.getString("portalCode");//门户接入号
    @Autowired
    protected BaseDao baseDao;

    private String db = ConfigUtil.getString("mh.webservice.db");

    /**
     * 查询学生基本信息
     *
     * @param clientAppId         加密的接入号
     * @param synchronizationtime 更新日期时间
     * @return List<ResourceEntity>
     */
    @Transactional(readOnly = true)
    public CommandResult getResourcesByStu(String clientAppId, String synchronizationtime) {
        if (StringUtil.isBlank(db)) {
            db = "apexu_jw";
        }
        CommandResult result = new CommandResult();
//      clientAppId = checkClientAppId(clientAppId); // 断言接入号正确
        String sqlColumn = "SELECT  xh," +
                " userid," +
                " name," +
                " ksh," +
                " sexid," +
                " sex," +
                " birthday," +
                " ictype," +
                " icno," +
                " collegecode," +
                " collegecodename," +
                " classcode," +
                " classname," +
                " grade," +
                " province," +
                " provincename," +
                " city," +
                " cityname," +
                " section," +
                " sectionname," +
                " jg," +
                " mzdm," +
                " mz," +
                " zzmmdm," +
                " zzmm," +
                " professioncode," +
                " professionname," +
                " type," +
                " typename," +
                " state," +
                " statename," +
                " ustype," +
                " ustypename," +
                " udate";
        String user_hql = " from " + db + ".Stu_Dsfjc t " +
                " where 1=1 ";
        if (StringUtil.isNotBlank(synchronizationtime)) {
            user_hql += " and udate>='" + synchronizationtime.replace(" ", "") + "'";
        }
        List<StuDsfjc> stuDsfjcs = DBUtil.queryAllBeanList(sqlColumn + user_hql, StuDsfjc.class);
        result.setStuDsfjcs(stuDsfjcs);
        return result;
    }


    /**
     * 查询教工基本信息
     *
     * @param clientAppId         加密的接入号
     * @param synchronizationtime 更新日期时间
     * @return List<ResourceEntity>
     */
    @Transactional(readOnly = true)
    public CommandResult getResourcesByJzg(String clientAppId, String synchronizationtime) {
        if (StringUtil.isBlank(db)) {
            db = "apexu_jw";
        }
        CommandResult result = new CommandResult();

//      clientAppId = checkClientAppId(clientAppId); // 断言接入号正确
        String sqlColumn = " SELECT userid," +
                "  name," +
                "  cym," +
                "  gh," +
                "  sfzjh," +
                "  zzjg," +
                "  xx," +
                "  jglb," +
                "  xb," +
                "  csrq," +
                "  province," +
                "  jg," +
                "  mz," +
                "  xl," +
                "  zc," +
                "  xw," +
                "  sfwp," +
                "  lxrq," +
                "  ustype," +
                "  ustypename," +
                "  udate";
        String user_hql = " from " + db + ".JZG_DSFJC t " +
                " where 1=1 ";
        if (StringUtil.isNotBlank(synchronizationtime)) {
            user_hql += " and udate<'" + synchronizationtime + "'";
        }
        List<JzgDsfjc> jzgDsfjcs = DBUtil.queryAllBeanList(sqlColumn + user_hql, JzgDsfjc.class);
        result.setJzgDsfjcs(jzgDsfjcs);
        return result;
    }

    /**
     * 查询教工基本信息
     *
     * @param clientAppId 加密的接入号
     * @return List<ResourceEntity>
     */
    @Transactional(readOnly = true)
    public CommandResult getResourcesByOrg(String clientAppId) {
        if (StringUtil.isBlank(db)) {
            db = "apexu_jw";
        }
        CommandResult result = new CommandResult();
//      clientAppId = checkClientAppId(clientAppId); // 断言接入号正确
        String sqlColumn = " SELECT id," +
                "fid," +
                "grade," +
                "type," +
                "orgtype," +
                "orgcode," +
                "name," +
                "describe," +
                "fdncode," +
                "dwlb," +
                "xq," +
                "dwdz," +
                "pxh," +
                "sfycx," +
                "jhbz," +
                "lmsj," +
                "lmwh," +
                "lmdzdwj," +
                "cxsj," +
                "cxwh," +
                "cxdzdwj," +
                "orgcategory," +
                "fcreatedate";
        String user_hql = " from " + db + ".ORG_DSFJC t " +
                " where 1=1 ";

        List<OrgDsfjc> orgDsfjcs = DBUtil.queryAllBeanList(sqlColumn + user_hql, OrgDsfjc.class);
        result.setOrgDsfjcs(orgDsfjcs);
        return result;
    }


    /**
     * 断言接入号合法性；断言接入站点就是登记注册时填写的网址
     *
     * @param clientAppId 加密的接入号
     * @return 解密后的接入号
     */
    public String checkClientAppId(String clientAppId) {

        if (StringUtils.isBlank(clientAppId)) {
            LOG.error("接收到一次非法的请求 [ miss ClientAppId ] ");
            throw new RuntimeException("非法请求！");
        } else {
            clientAppId = CipherUtil.decryptByAES(clientAppId); // 解密
            String cacheKey = "AuthApp" + clientAppId;
            TAccessAppReg appReg = (TAccessAppReg) CacheUtils.get(cacheKey); // 缓存
            if (appReg == null) {
                List<TAccessAppReg> appRegs = baseDao.findByHqlWithSecondCache(true, "from TAccessDatabaseReg where appid=?", clientAppId);
                if (appRegs == null || appRegs.isEmpty()) {
                    LOG.error("接收到一次无效的请求 [ not exist ClientAppId : " + clientAppId + " ] ");
                    throw new RuntimeException("无效请求！");
                } else { // 缓存起来
                    CacheUtils.put(cacheKey, appRegs.get(0));
                }
            }
        }
        return clientAppId;
    }

}
